package com.api.workflow.web;


import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;

/**
 * @author wanghan
 * @version 1.0
 * @Description 客户授信额度
 * @since 2025/2/27 12:29
 */
public class CustomerCreditAction extends BaseBean implements Action{

  private String khbm;
  private String sxnd;
  private String sxze;
  private String sxxglc;
  private String sxxyd;

    public String getKhbm() {
        return khbm;
    }

    public void setKhbm(String khbm) {
        this.khbm = khbm;
    }

    public String getSxnd() {
        return sxnd;
    }

    public void setSxnd(String sxnd) {
        this.sxnd = sxnd;
    }

    public String getSxze() {
        return sxze;
    }

    public void setSxze(String sxze) {
        this.sxze = sxze;
    }

    public String getSxxglc() {
        return sxxglc;
    }

    public void setSxxglc(String sxxglc) {
        this.sxxglc = sxxglc;
    }

    public String getSxxyd() {
        return sxxyd;
    }

    public void setSxxyd(String sxxyd) {
        this.sxxyd = sxxyd;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            writeLog("start------------------------ContractTriggersProcurementAction");
            //获得流程id
            String workflowid = requestInfo.getWorkflowid();
            //获取表id
            String requestid = requestInfo.getRequestid();
            writeLog("start------------------------ContractTriggersProcurementAction" + requestid);
            RecordSet rs = new RecordSet();
            rs.execute("select tablename from workflow_base a,workflow_bill b where a.formid=b.id and a.id=" + workflowid);
            rs.next();
            //获取主表名
            String maintable = Util.null2String(rs.getString("tablename"));

            //根据表id和主表名查找主表的相关信息
            rs.executeQuery("select * from " + maintable + " where requestid=?", new Object[]{requestid});
            rs.next();
            String khbmvalue = Util.null2String(rs.getString(this.khbm));//客户编码
            String sxndvalue = Util.null2String(rs.getString(this.sxnd));//授信年度
            String sxzevalue = Util.null2String(rs.getString(this.sxze));//授信总额
            String sxxglcvalue = Util.null2String(rs.getString(this.sxxglc));//授信相关流程
            String sxxydvalue = Util.null2String(rs.getString(this.sxxyd));//授信信用段
            int modeId = getModeId("uf_khsxxx");
            Map<String, Object> filedMap = new HashMap<>();
            filedMap.put("khbm",khbmvalue);
            filedMap.put("sxnd",sxndvalue);
            filedMap.put("sxze",sxzevalue);
            filedMap.put("sxxglc",sxxglcvalue);
            filedMap.put("sxxyd",sxxydvalue);
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("khbm",khbmvalue);
            updateMap.put("sxxyd",sxxydvalue);
            rs.executeQuery("select * from uf_khsxxx where khbm =? and sxxyd=? and sxnd=?",khbmvalue,sxxydvalue,sxndvalue);
            rs.next();
            int size = rs.getArray().size();
            if (size==0){
                boolean b = insetModeData("uf_khsxxx", filedMap, 1, modeId);
            }else {
                Double sxzelsvalue = Double.valueOf(Util.null2String(rs.getString("sxze")));
                sxzelsvalue=sxzelsvalue+Double.valueOf(sxzevalue);
                String sxxglclsvalue = Util.null2String(rs.getString("sxxglc"));
                if (StringUtil.isNullOrEmpty(sxxglclsvalue)){
                    sxxglclsvalue=requestid;
                }else {
                    sxxglclsvalue=sxxglclsvalue+","+requestid;
                }
                writeLog("sxzelsvaluesxzelsvalue" + sxzelsvalue);
                writeLog("sxxglclsvaluesxxglclsvalue" + sxxglclsvalue);
                rs.executeUpdate("update uf_khsxxx set sxze=?,sxxglc=? where  khbm =? and sxxyd=? and sxnd=? ",sxzelsvalue,sxxglclsvalue,khbmvalue,sxxydvalue,sxndvalue);
            }
            return Action.SUCCESS;

        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent("接口出错,请联系管理员!"+e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
    }

    /**
     *
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }

    /**
     * 插入到建模表数据
     * @param tableName
     * @param data
     * @param hrmResourceId
     * @param modeId
     * @return
     * @throws Exception
     */
    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            columns += (key + ",");
            values += ("?,");
            dataList.add(value);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }
    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }
}
